<script setup>
import {onMounted, ref} from "vue";
import {ElMessage, ElMessageBox, ElTable} from 'element-plus'
import axios from "axios";
import { format } from 'date-fns'; // 引入 date-fns 库用于格式化日期


let input1 = ref("");
let input2 = ref("");
let input3 = ref("");
let tableData = ref([]);
let centerDialogVisible = ref(false);
let courseTypeOptions = ref([]);//课程类型列表
let consultantOptions = ref([]);//咨询师列表
const value = ref(false)
let total = ref(0); // 总数据量，初始化为0
const pageNum = ref(1); // 当前页码
const pageSize = ref(10); // 每页显示的数据量
// 分页事件处理
const handlePageChange = (newPage) => {
  pageNum.value = newPage; // 更新当前页码
  refreshTableData(); // 重新请求数据
};
//弹框修改显示的值
let from = ref({
  audioId:null,
  fileName:'',
  imageUrl:'',
  title:'',
  coursetype:'',
  typeId:null,
  consultantId:null,
  uploadTime:'',
  consultantName:'',
  consultantRealname:'',

})



// 每页显示数量发生改变时触发
const handleSizeChange = (size) => {
  pageSize.value = size; // 更改请求参数中的pageSize
  pageNum.value = 1; // 设置当改变后，默认访问第一页
  refreshTableData(); // 重新查询数据
};

// 页码发生改变时触发
const handleCurrentChange = (num) => {
  pageNum.value = num; // 更新当前页码
  refreshTableData(); // 重新查询数据
};

//批量删除获取id
let selectedAudioIds = ref([]); // 存储选中的音频 ID

const handleSelectionChange = (selection) => {
  selectedAudioIds.value = selection.map(item => item.audioId);
};
//模糊查询
const searchAudio = () => {

  axios.get("/audio/info", {
    params: {
      title: input1.value,
      consultantRealname: input2.value,
      courseTypeName: input3.value,
      // consultant: {
      //    realname:input2.value
      // },
      // consultant.realname:input2.value
      // coursetype:{
      //   coursetype:input3.value,
      // }
    }
  })
      .then((resp) => {
        tableData.value = resp.data.data;
        // total.value = resp.data.data.total;
        console.log("查询结果：", tableData.value);
        console.log("当前页码:",pageNum.value);
        console.log("每页数量:", pageSize.value);
        // console.log("总数据量:", total.value);
      })
      .catch((err) => {
        console.error("查询失败：", err);
      });
};


// 重置搜索框并刷新表格数据
const resetSearch = () => {
  input1.value = '';
  input2.value = '';
  input3.value = '';
  refreshTableData(); // 调用刷新表格数据的方法
};



// 获取课程类型列表
const getCourseTypeOptions = () => {
  axios.get("/coursetype") // 假设这是获取课程类型的 API
      .then((resp) => {
        courseTypeOptions.value = resp.data.data;
        console.log("课程类型列表");
        console.log(resp.data.data);
      })
      .catch((err) => {
        ElMessage.error("获取课程类型失败：" + err.message);
      });
};

// 获取咨询师列表
const getConsultantOptions = () => {
  axios.get("/consultant/findAllConsultant2") // 假设这是获取咨询师的 API
      .then((resp) => {
        consultantOptions.value = resp.data.data;
      })
      .catch((err) => {
        ElMessage.error("获取咨询师失败：" + err.message);
      });
};



// 获取表格数据的函数
const refreshTableData = () => {
  axios.get("/audio/list",
      {
        params: {
          pageNum: pageNum.value,
          pageSize: pageSize.value,
        }
      }
  )
      .then((resp) => {
        tableData.value = resp.data.data.list;
        total.value=resp.data.data.total
        console.log("总数")
        console.log(total.value);
        console.log(pageNum.value);
        console.log(pageSize.value);
        console.log("这是总的数据信息");
        console.log(tableData.value);
        console.log(resp.data.data);
      })
      .catch((err) => {
        console.error(err);
      });
};
// 刷新页面
onMounted(() => {
  refreshTableData();
  getCourseTypeOptions();
  getConsultantOptions();
});
// //删除这一条数据
// const deleteRow = (id) => {
//   console.log("delete...", id);
//   axios.delete(`/audio?id=${id}`)
//       .then((resp) => {
//         console.log(resp);
//         refreshTableData();
//         // 重新获取数据或更新tableData
//       })
//       .catch((err) => {
//         console.log(axios.delete(`/audio/${id}`));
//         console.log(err);
//       });
// };
// 删除这一条数据
const deleteRow = (id) => {
  // 将当前要删除的音频 ID 添加到批量删除的数组中
  selectedAudioIds.value.push(id);

  // 调用批量删除接口
  batchDelete();
};
// =====================================================================
//点就修改按钮后，更新from为该行数据
const updateRow = (row)=>{

    centerDialogVisible.value = true;
    console.log("这一行元素")

    from.value = {
      audioId: row.audioId, //音频id
      fileName: row.fileName, //音频名
      imageUrl: row.imageUrl, //音频图片
      title: row.title,
      typeId: row.coursetype.typeId,
      coursetype: row.coursetype.name,
      consultantId: row.consultantId,
      uploadTime: row.uploadTime,
      consultantRealname: row.consultant.realname,
      consultantName: row.consultant.username,
    }
  console.log(from.value)

}


// 确认添加或修改数据
const confirm = async () => {
  console.log("确认操作...");
  console.log(from.value)
  if (!from.value.fileName || !from.value.imageUrl) {
    ElMessage.error('请先上传音频和头像');
    return;
  }

  try {
    let response;
    if (from.value.audioId) {
      // 确保 uploadTime 是 Date 对象
      if (typeof from.value.uploadTime === 'string') {
        from.value.uploadTime = new Date(from.value.uploadTime);
      }
      console.log("修改之前"+ JSON.stringify(from.value, null, 2))
      // 修改操作
      response = await axios.put("/audio", {
        audioId: from.value.audioId,
        fileName: from.value.fileName, // 音频名
        imageUrl: from.value.imageUrl, // 音频图片
        title: from.value.title,
        typeId: from.value.typeId,
        consultantId: from.value.consultantId,
            uploadTime: format(from.value.uploadTime, 'yyyy-MM-dd HH:mm:ss'), // 格式化为字符串
      },
          {
            headers: {"Content-Type": " application/json"},
          }
      );
    } else {
      console.log("添加输入"+from.value)
      // 添加操作
      response = await axios.post("/audio", {
        fileName: from.value.fileName, // 音频名
        imageUrl: from.value.imageUrl, // 音频图片
        title: from.value.title,
        typeId: from.value.typeId,
        consultantId: from.value.consultantId,
        uploadTime: format(new Date(), 'yyyy-MM-dd HH:mm:ss'), // 格式化为字符串

      });

    }

    if (response.data) {
      ElMessage({
        type: 'success',
        message: '操作成功'
      });
      refreshTableData();
      centerDialogVisible.value = false;
    } else {
      ElMessage({
        type: 'error',
        message: '操作失败，请稍后再试'
      });
    }
  } catch (error) {
    console.error(error);
    if (error.response) {
      // 请求已发出，但服务器响应的状态码不在 2xx 范围内
      ElMessage.error(`操作过程中发生错误: ${error.response.data.message || error.response.statusText}`);
    } else if (error.request) {
      // 请求已发出，但没有接收到响应
      ElMessage.error('未接收到响应，请检查网络连接');
    } else {
      // 发生了设置请求时触发的错误
      ElMessage.error('请求设置错误，请检查代码');
    }
  }
};
// 当选择课程类型时，更新课程 ID
const onCourseTypeChange = (newValue) => {
  const selectedCourseType = courseTypeOptions.value.find(courseType => courseType.name === newValue);
  if (selectedCourseType) {
    from.value.typeId = selectedCourseType.typeId;
  }
};

// 当选择咨询师用户名时，更新咨询师 ID 和姓名
const onConsultantNameChange = (newValue) => {
  const selectedConsultant = consultantOptions.value.find(consultant => consultant.username === newValue);
  if (selectedConsultant) {
    from.value.consultantId = selectedConsultant.consultantId;
    from.value.consultantRealname = selectedConsultant.realname;
  }
};

// 添加数据
const addRow = () => {
  centerDialogVisible.value = true;
  // 重置表单数据
  from.value = {
    audioId: null,
    fileName: '',
    imageUrl: '',
    title: '',
    coursetype: '',
    typeId: null,
    consultantId: null,
    uploadTime: '',
    consultantName: '',
    consultantRealname: '',
  };
};


// 上传头像的方法
const uploadAvatar = async (options) => {
  const file = options.file;
  if (!['image/jpeg', 'image/png', 'image/gif'].includes(file.type)) {
    ElMessage.error('图片格式必须是 JPG、PNG 或 GIF');
    return;
  }

  const formData = new FormData();
  formData.append('file', file);

  try {
    const response = await axios.post('/file', formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    });

    if (response.data) {
      // 更新表单中的头像 URL
      from.value.imageUrl = response.data;
      ElMessage({
        type: 'success',
        message: '头像上传成功'
      });
    } else {
      ElMessage({
        type: 'error',
        message: '头像上传失败，请稍后再试'
      });
    }
  } catch (error) {
    console.error('上传过程中发生错误:', error);
    ElMessage({
      type: 'error',
      message: '上传过程中发生错误'
    });
  }
};

// 上传音频的方法
const uploadAudio = async (options) => {
  const file = options.file;
  if (!['audio/mpeg', 'audio/mp3'].includes(file.type)) {
    ElMessage.error('音频格式必须是 MP3');
    return;
  }

  const formData = new FormData();
  formData.append('file', file);

  try {
    const response = await axios.post('/file', formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    });

    if (response.data) {
      // 更新表单中的音频 URL
      from.value.fileName = response.data;
      ElMessage({
        type: 'success',
        message: '音频上传成功'
      });
    } else {
      ElMessage({
        type: 'error',
        message: '音频上传失败，请稍后再试'
      });
    }
  } catch (error) {
    console.error('上传过程中发生错误:', error);
    ElMessage({
      type: 'error',
      message: '上传过程中发生错误'
    });
  }
};


//批量删除
const batchDelete = () => {
  if (selectedAudioIds.value.length === 0) {
    ElMessage.error('请选择要删除的音频');

    return;
  }

  ElMessageBox.confirm(
      '确定要删除选中的音频吗？',
      '批量删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
  ).then(() => {
    console.log("删除的id")
    console.log(selectedAudioIds.value)
    axios.delete('/audio', {
      data: selectedAudioIds.value

    }).then((resp) => {

      ElMessage.success('删除成功');
      refreshTableData(); // 重新加载数据
    }).catch((err) => {
      ElMessage.error('删除失败: ' + err.message);
    });
  }).catch(() => {
    ElMessage.info('已取消删除');
  });
};

</script>

<template>
<!--搜索框-->
  <div class="title">
    标题
    <el-input v-model="input1" style="width: 240px" placeholder="Please input" />
    咨询师姓名
    <el-input v-model="input2" style="width: 240px" placeholder="Please input" />
    一级课程类型
    <el-input v-model="input3" style="width: 240px" placeholder="Please input" />
    <el-button type="success" class="search" @click="searchAudio">搜索</el-button>
    <el-button type="warning" @click="resetSearch">重置</el-button>
  </div>
  <!--    添加和批量删除按钮-->
  <div class="addbtn">
    <el-button type="success" @click="addRow">添加</el-button>
    <el-button type="danger" @click="batchDelete">批量删除</el-button>
  </div>
<!--  表格-->
  <div class="table">
    <el-table :data="tableData" style="width: 90%" height="400"  ref="multipleTable" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column property="audioId" label="音频编号" width="100" />
      <el-table-column label="图片" width="160">
        <template #default="scope">
          <img :src="scope.row.imageUrl" style="width: 100px; height: auto;" />
        </template>
      </el-table-column>
      <el-table-column label="音频" width="240">
        <template #default="scope">
          <audio :src="scope.row.fileName" controls style="width: 100%;" />
        </template>
      </el-table-column>
      <el-table-column property="title" label="标题" width="120" />
      <el-table-column property="coursetype.name" label="一级课程类型" width="120" />
      <el-table-column property="consultant.username" label="咨询师用户名" width="120" />
      <el-table-column property="consultant.realname" label="咨询师姓名" width="120" />
      <el-table-column property="uploadTime" label="上传时间" width="120" />
      <el-table-column label="操作" width="240">

        <template #default="scope">
          <el-button type="warning" @click="updateRow(scope.row)">修改</el-button>
          <el-button type="danger" @click="deleteRow(scope.row.audioId)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>

<!--  分页-->
<!--   分页-->
<!--  <div>-->
<!--    <el-pagination-->
<!--        :current-page="pageNum.value"-->
<!--        :page-size="pageSize.value"-->
<!--        :total=total.value-->
<!--        layout="prev, pager, next"-->
<!--        @current-change="handlePageChange"-->
<!--    />-->
<!--  </div>-->

  <!-- 分页区域 -->
  <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="pageNum.value" :page-sizes="[5, 10, 15, 20]" :page-size="pageSize.value" layout="total, sizes, prev, pager, next, jumper" :total="total"></el-pagination>

<!--  弹窗的对话框-->
  <div>
    <el-dialog v-model="centerDialogVisible" title="添加新音频" width="500" center>
<div class="content">


  <el-form-item label="头像" :label-width="100">
    <el-upload
        class="avatar-uploader"
        action="http://localhost:8085/file"
        :show-file-list="false"
        :before-upload="beforeAvatarUpload"
        :http-request="uploadAvatar"
        v-if="centerDialogVisible"
    >
      <img v-if="from.imageUrl" :src="from.imageUrl" class="avatar" alt="头像">
      <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
    </el-upload>
  </el-form-item>

  <el-form-item label="音频" :label-width="100">
    <el-upload
        class="audio-uploader"
        action="http://localhost:8085/file"
        :show-file-list="false"
        :before-upload="beforeAudioUpload"
        :http-request="uploadAudio"
        v-if="centerDialogVisible"
    >
      <el-button slot="trigger" size="small" type="primary">选取音频</el-button>
    </el-upload>
    <audio v-if="from.fileName" controls :src="from.fileName"></audio>
  </el-form-item>
    <div> 音频标题   <el-input v-model="from.title" style="width: 240px" placeholder="Please input" /></div>
<!--      <div>  课程类型   <el-input v-model="from.coursetype" style="width: 240px" placeholder="Please input" /></div>-->
<!--      <div>  咨询师用户名   <el-input v-model="from.consultantName" style="width: 240px" placeholder="Please input" /></div>-->


  <div> 课程类型
    <el-select v-model="from.coursetype" placeholder="请选择课程类型" style="width: 240px" @change="onCourseTypeChange">
      <el-option
          v-for="item in courseTypeOptions"
          :key="item.typeId"
          :label="item.name"
          :value="item.name">
      </el-option>
    </el-select>
  </div>
  <div> 咨询师用户名
    <el-select v-model="from.consultantName" placeholder="请选择咨询师" style="width: 240px" @change="onConsultantNameChange">
      <el-option
          v-for="item in consultantOptions"
          :key="item.username"
          :label="item.username"
          :value="item.username">
      </el-option>
    </el-select>
  </div>
        <div>  咨询师姓名   <el-input v-model="from.consultantRealname" style="width: 240px" placeholder="Please input" /></div>
<!--          <div>  上传时间   <el-input v-model="from.uploadTime" style="width: 240px" placeholder="Please input" /></div>-->
</div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="centerDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirm" >
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>



.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.avatar-uploader {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
.title{
  margin-top: 20px;
  margin-left: 20px;
}
.search{
  margin-left: 10px;
}
.addbtn{
  margin: 30px;

}
.table{
  margin-left: 50px;
}
.content>div{
  margin-top: 20px;
  margin-left: 30px;
}
</style>